package com.ly.blog_data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.blog_common.constant.Constant;
import com.ly.blog_common.entity.ChapterEntity;
import com.ly.blog_common.entity.InfoEntity;
import com.ly.blog_common.response.BlogException;
import com.ly.blog_common.security.SecurityUtils;
import com.ly.blog_common.utils.PageUtils;
import com.ly.blog_common.utils.Query;
import com.ly.blog_common.utils.R;
import com.ly.blog_data.dao.DataResultDao;
import com.ly.blog_data.entity.DataResultEntity;
import com.ly.blog_data.entity.DataTaskEntity;
import com.ly.blog_data.feign.ArticleService;
import com.ly.blog_data.service.DataResultService;
import com.ly.blog_data.service.DataTaskService;
import com.ly.blog_data.vo.DataResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("dataResultService")
public class DataResultServiceImpl extends ServiceImpl<DataResultDao, DataResultEntity> implements DataResultService {

    @Autowired
    private DataTaskService dataTaskService;

    @Autowired
    private ArticleService articleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper queryWrapper = new QueryWrapper<DataResultEntity>();
        String userId = SecurityUtils.getUserId();
        if(!String.valueOf(Constant.SUPER_ADMIN).equals(userId)){
            queryWrapper.eq("create_by",userId);
        }

        IPage<DataResultEntity> page = this.page(
            new Query<DataResultEntity>().getPage(params),
            queryWrapper
        );

        IPage<DataResultVo> pageVo = new Page<>();
        pageVo.setCurrent(page.getCurrent());
        pageVo.setSize(page.getSize());
        pageVo.setTotal(page.getTotal());
        pageVo.setPages(page.getPages());
        pageVo.setRecords(page.getRecords().stream().map(item->{

            DataTaskEntity dataTaskEntity = dataTaskService.getById(item.getTaskId());

            Integer isPush = 0;
            try {
                isPush = articleService.articlePushResult(dataTaskEntity.getId());
            }catch (Exception e){

            }
            DataResultVo dataResultVo = DataResultVo.builder()
                .id(item.getId())
                .content(item.getContent())
                .exeUrl(item.getExeUrl())
                .state(item.getState())
                .taskId(item.getTaskId())
                .title(item.getTitle())
                .createBy(item.getCreateBy())
                .createTime(item.getCreateTime())
                .lastUpdateBy(item.getLastUpdateBy())
                .lastUpdateTime(item.getLastUpdateTime())

                .taskName(dataTaskEntity.getName())
                .taskType(dataTaskEntity.getType())
                //检测文章获取文章是否推送 0,没有推送 ； 1，推送了
                .isPush(isPush)

                .build();
            return dataResultVo;
        }).collect(Collectors.toList()));

        return new PageUtils(pageVo);
    }

    /**
     * @param id
     * @param pushType 0/全部 1/单个
     */
    @Override
    public void push(Integer id, Integer pushType) {

        //是否展示 - 默认不展示
        final Integer isShow = 1;

        DataResultEntity resultEntity = this.getById(id);
        DataTaskEntity taskEntity = dataTaskService.getById(resultEntity.getTaskId());

        Integer type = taskEntity.getType();

        //初始化文章信息
        InfoEntity infoEntity = new InfoEntity();
        infoEntity.setAuthor("来源网络");
        infoEntity.setIsShow(isShow);
        infoEntity.setWatchTime(1L);


        //新闻直接推送
        if(type == 0){
            //抓取 - 新闻类
            infoEntity.setCatId(13L);
            infoEntity.setShowImg("");
            infoEntity.setTitle(resultEntity.getTitle());
            R r = articleService.articleSave(infoEntity);
            if(r.getCode()!=0){
                throw new BlogException(r.getMsg(),r.getCode());
            }
            ChapterEntity chapterEntity = new ChapterEntity();
            Long articleId = Long.parseLong(String.valueOf(r.get("id")));
            chapterEntity.setInfoId(articleId);
            chapterEntity.setWatchTime(1L);
            chapterEntity.setChapterName("");
            chapterEntity.setContent(resultEntity.getContent());
            chapterEntity.setIsShow(isShow);
            chapterEntity.setOrderNumber(resultEntity.getId().longValue());

            chapterEntity.setSourceId(resultEntity.getId());

            r = articleService.chapterSave(chapterEntity);
            if(r.getCode()!=0){
                throw new BlogException(r.getMsg(),r.getCode());
            }
        }

        //小说直接全部推送
        if(type == 1){
            infoEntity.setCatId(17L); //小说 - 玄幻
            infoEntity.setShowImg("");
            infoEntity.setTitle(taskEntity.getName());
            R r = articleService.articleSave(infoEntity);

            if(1 == pushType){
                ChapterEntity chapterEntity = new ChapterEntity();
                Long articleId = Long.parseLong(String.valueOf(r.get("id")));
                chapterEntity.setInfoId(articleId);
                chapterEntity.setWatchTime(1L);
                chapterEntity.setChapterName("");
                chapterEntity.setContent(resultEntity.getContent());
                chapterEntity.setIsShow(isShow);
                chapterEntity.setOrderNumber(resultEntity.getId().longValue());

                chapterEntity.setSourceId(resultEntity.getId());

                articleService.chapterSave(chapterEntity);
            }else{
                //推送全部小说
                List<DataResultEntity> resultEntities =
                        this.list(new QueryWrapper<DataResultEntity>().eq("task_id", resultEntity.getTaskId()));
                resultEntities.forEach(item ->{
                    ChapterEntity chapterEntity = new ChapterEntity();
                    Long articleId = Long.parseLong(String.valueOf(r.get("id")));
                    chapterEntity.setInfoId(articleId);
                    chapterEntity.setWatchTime(1L);
                    chapterEntity.setChapterName(item.getTitle());
                    chapterEntity.setContent(item.getContent());
                    chapterEntity.setIsShow(isShow);
                    chapterEntity.setOrderNumber(item.getId().longValue());

                    chapterEntity.setSourceId(item.getId());

                    articleService.chapterSave(chapterEntity);
                });
            }
        }


    }
}